﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace TFSCommon.TFS
{
    class TfsConnector
    {
        public bool IsTfs2010 { get; private set; }
        private String Server { get; set; }
        private String Collection { get; set; }

        public TfsConnector(string server)
            : this(server, string.Empty)
        { }

        public TfsConnector(string server, string collection)
        {
            Set(server, collection);
        }

        public void Set(string server)
        {
            Set(server, string.Empty);
        }

        public void Set(string server, string collection)
        {
            Server = server;
            Collection = collection;

            TfsConnection connection = TfsConfigurationServerFactory.GetConfigurationServer(RegisteredTfsConnections.GetConfigurationServer(server));
            connection.EnsureAuthenticated();

            WorkItemStore store = connection.GetService<WorkItemStore>();

            IsTfs2010 = (null == store);
        }

        public TfsConnection GetServerConnection()
        {
            TeamProjectPicker p = new TeamProjectPicker();
            p.ShowDialog();
            return TfsConfigurationServerFactory.GetConfigurationServer(RegisteredTfsConnections.GetConfigurationServer(Server));
        }

        public TfsConnection GetWorkItemConnection()
        {
            if (IsTfs2010)
            {
                return TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(Collection));
            }

            return GetServerConnection();
        }
    }
}
